import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:flutter/widgets.dart';

const supportedLocales = [
  Locale('en'),
  Locale('zh'),
];

class AppLocalizations {
  final Locale locale;

  AppLocalizations(this.locale);

  static AppLocalizations? of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  static Map<String, Map<String, String>> _localizedStrings = {
    'en': {},
    'zh': {},
  };

  Future<bool> load() async {
    final jsonStr = await rootBundle.loadString('lib/l10n/app_${locale.languageCode}.arb');
    Map<String, dynamic> jsonMap = json.decode(jsonStr);
    
    _localizedStrings[locale.languageCode] = jsonMap.map((key, value) {
      if (value is Map) {
        return MapEntry(key, value['message']?.toString() ?? key);
      }
      return MapEntry(key, value.toString());
    });
    
    return true;
  }

  // 基础翻译方法
  String translate(String key, {Map<String, String>? params}) {
    String value = _localizedStrings[locale.languageCode]?[key] ?? key;
    
    if (params != null) {
      params.forEach((paramKey, paramValue) {
        value = value.replaceAll('{$paramKey}', paramValue);
      });
    }
    
    return value;
  }

  // 带数量的复数翻译
  String plural(String key, int count, {Map<String, String>? params}) {
    final baseValue = translate(key, params: params);
    
    // 解析复数规则
    final parts = baseValue.split('|');
    if (parts.length > 1) {
      if (count == 0 && parts.length > 2) return parts[0];
      if (count == 1) return parts[1];
      return parts.last;
    }
    
    return baseValue.replaceAll('{count}', count.toString());
  }

  // 带格式的日期翻译
  String formatDate(DateTime date, {String format = 'yyyy/MM/dd'}) {
    return DateFormat(format, locale.languageCode).format(date);
  }

  // 带格式的时间翻译
  String formatTime(DateTime time, {String format = 'HH:mm'}) {
    return DateFormat(format, locale.languageCode).format(time);
  }

  // 带格式的日期时间翻译
  String formatDateTime(DateTime dateTime, {String format = 'yyyy/MM/dd HH:mm'}) {
    return DateFormat(format, locale.languageCode).format(dateTime);
  }
}

class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localizations = AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

  @override
  bool shouldReload(_AppLocalizationsDelegate old) => false;
}

extension LocalizationsExt on BuildContext {
  AppLocalizations get l10n => AppLocalizations.of(this)!;
} 